﻿import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/common/utils/toast_util.dart';
import 'package:image_picker/image_picker.dart';
import 'package:azring/core/repository/default_api.dart';

class SettingsProfileLogic extends GetxController {
  final avatarUrl = ''.obs;
  final nickname = ''.obs;
  final career = ''.obs;
  final birthday = ''.obs;
  final gender = ''.obs;
  final height = 0.obs;
  final weight = 0.obs;

  final ImagePicker _picker = ImagePicker();

  @override
  void onInit() {
    super.onInit();
    loadUserInfo();
  }

  /// 加载用户信息
  Future<void> loadUserInfo() async {
    try {
      final response = await DefaultApi().queryUserGet();
      if (response != null && response['code'] == 200) {
        final data = response['data'];
        nickname.value = data['nickName'] ?? '';
        career.value = data['career'] ?? '';
        birthday.value = data['birthday'] ?? '';
        // 性别：1-男，0-女
        final sexValue = data['sex'];
        if (sexValue != null) {
          gender.value = sexValue == 1 || sexValue == '1' ? '男' : '女';
        }
        // 处理身高和体重，可能是int或double类型
        final heightValue = data['height'];
        height.value = heightValue != null
            ? (heightValue is int ? heightValue : (heightValue as num).toInt())
            : 0;

        final weightValue = data['weight'];
        weight.value = weightValue != null
            ? (weightValue is int ? weightValue : (weightValue as num).toInt())
            : 0;

        // 处理头像URL - 拼接完整地址
        final avatar = data['avatar'];
        if (avatar != null && avatar.toString().isNotEmpty) {
          if (avatar.toString().startsWith('http')) {
            avatarUrl.value = avatar;
          } else {
            // 拼接基础URL
            avatarUrl.value = 'https://api.azlg.com/prod-api$avatar';
          }
        }
      }
    } catch (e) {
      print('加载用户信息失败: $e');
    }
  }

  /// 选择头像
  Future<void> pickAvatar() async {
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Color(0xFF2A2A2A),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: const Icon(Icons.camera_alt, color: Colors.white),
                title: const Text('拍照', style: TextStyle(color: Colors.white)),
                onTap: () async {
                  Get.back();
                  final XFile? image = await _picker.pickImage(
                    source: ImageSource.camera,
                    maxWidth: 800,
                    maxHeight: 800,
                    imageQuality: 85,
                  );
                  if (image != null) {
                    await _uploadAvatar(File(image.path));
                  }
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo_library, color: Colors.white),
                title:
                    const Text('从相册选择', style: TextStyle(color: Colors.white)),
                onTap: () async {
                  Get.back();
                  final XFile? image = await _picker.pickImage(
                    source: ImageSource.gallery,
                    maxWidth: 800,
                    maxHeight: 800,
                    imageQuality: 85,
                  );
                  if (image != null) {
                    await _uploadAvatar(File(image.path));
                  }
                },
              ),
              ListTile(
                leading: const Icon(Icons.cancel, color: Colors.white),
                title: const Text('取消', style: TextStyle(color: Colors.white)),
                onTap: () => Get.back(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 选择性别
  void selectGender() {
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Color(0xFF282528),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                title: const Text('男',
                    style: TextStyle(color: Colors.white),
                    textAlign: TextAlign.center),
                onTap: () {
                  gender.value = '男';
                  Get.back();
                  _updateUserInfo();
                },
              ),
              const Divider(height: 1, color: Color(0xFF1A1A1A)),
              ListTile(
                title: const Text('女',
                    style: TextStyle(color: Colors.white),
                    textAlign: TextAlign.center),
                onTap: () {
                  gender.value = '女';
                  Get.back();
                  _updateUserInfo();
                },
              ),
              const Divider(height: 1, color: Color(0xFF1A1A1A)),
              ListTile(
                title: const Text('取消',
                    style: TextStyle(color: Colors.white),
                    textAlign: TextAlign.center),
                onTap: () => Get.back(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 上传头像
  Future<void> _uploadAvatar(File imageFile) async {
    try {
      Get.dialog(
        const Center(child: CircularProgressIndicator()),
        barrierDismissible: false,
      );

      final response = await DefaultApi().uploadAvatarPost(
        avatarFile: imageFile,
        isShowLoading: false,
      );

      Get.back(); // 关闭loading

      if (response != null && response['code'] == 200) {
        // 从返回结果中获取imgUrl
        final imgUrl = response['imgUrl'];
        if (imgUrl != null && imgUrl.toString().isNotEmpty) {
          // 拼接完整的头像URL
          if (imgUrl.toString().startsWith('http')) {
            avatarUrl.value = imgUrl;
          } else {
            avatarUrl.value = 'https://api.azlg.com/prod-api$imgUrl';
          }
          Toast.show('头像上传成功');
        }
      } else {
        Toast.show('头像上传失败，请重试');
      }
    } catch (e) {
      Get.back(); // 关闭loading
      print('上传头像失败: $e');
      Toast.show('头像上传失败：$e');
    }
  }

  /// 更新用户信息到服务器
  Future<void> _updateUserInfo() async {
    try {
      // 性别需要转换：男-1，女-0
      final sexValue = gender.value == '男' ? 1 : 0;

      final response = await DefaultApi().editUserPut(
        sex: sexValue,
        height: height.value > 0 ? height.value : null,
        weight: weight.value > 0 ? weight.value : null,
        birthday: birthday.value.isNotEmpty ? birthday.value : null,
        isShowLoading: true,
      );

      if (response != null && response['code'] == 200) {
        Toast.show('信息已更新');
      } else {
        Toast.show('更新失败，请重试');
      }
    } catch (e) {
      print('更新用户信息失败: $e');
      Toast.show('更新失败：$e');
    }
  }

  /// 更新昵称
  Future<void> updateNickname(String newNickname) async {
    try {
      final response = await DefaultApi().editUserPut(
        nickName: newNickname,
        isShowLoading: true,
      );

      if (response != null && response['code'] == 200) {
        nickname.value = newNickname;
      }
    } catch (e) {
      print('更新昵称失败: $e');
    }
  }

  /// 更新职业
  Future<void> updateCareer(String newCareer) async {
    try {
      final response = await DefaultApi().editUserPut(
        career: newCareer,
        isShowLoading: true,
      );

      if (response != null && response['code'] == 200) {
        career.value = newCareer;
      }
    } catch (e) {
      print('更新职业失败: $e');
    }
  }

  /// 选择生日
  void selectBirthday() {
    Get.bottomSheet(
      Container(
        height: 300,
        decoration: const BoxDecoration(
          color: Color(0xFF2A2A2A),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(
                  onPressed: () => Get.back(),
                  child:
                      const Text('取消', style: TextStyle(color: Colors.white)),
                ),
                TextButton(
                  onPressed: () {
                    Get.back();
                    _updateUserInfo();
                  },
                  child: const Text('确定',
                      style: TextStyle(color: Color(0xFF007AFF))),
                ),
              ],
            ),
            Expanded(
              child: Theme(
                data: ThemeData.dark(),
                child: CalendarDatePicker(
                  initialDate: DateTime.now(),
                  firstDate: DateTime(1900),
                  lastDate: DateTime.now(),
                  onDateChanged: (date) {
                    birthday.value =
                        '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} 00:00:00';
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 选择身高
  void selectHeight() {
    int selectedHeight = height.value > 0 ? height.value : 170;
    Get.bottomSheet(
      Container(
        height: 300,
        decoration: const BoxDecoration(
          color: Color(0xFF2A2A2A),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(
                  onPressed: () => Get.back(),
                  child:
                      const Text('取消', style: TextStyle(color: Colors.white)),
                ),
                TextButton(
                  onPressed: () {
                    height.value = selectedHeight;
                    Get.back();
                    _updateUserInfo();
                  },
                  child: const Text('确定',
                      style: TextStyle(color: Color(0xFF007AFF))),
                ),
              ],
            ),
            Expanded(
              child: ListWheelScrollView.useDelegate(
                itemExtent: 50,
                diameterRatio: 1.5,
                physics: const FixedExtentScrollPhysics(),
                onSelectedItemChanged: (index) {
                  selectedHeight = 100 + index;
                },
                childDelegate: ListWheelChildBuilderDelegate(
                  builder: (context, index) {
                    return Center(
                      child: Text(
                        '${100 + index} cm',
                        style:
                            const TextStyle(color: Colors.white, fontSize: 20),
                      ),
                    );
                  },
                  childCount: 151, // 100-250cm
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 选择体重
  void selectWeight() {
    int selectedWeight = weight.value > 0 ? weight.value : 60;
    Get.bottomSheet(
      Container(
        height: 300,
        decoration: const BoxDecoration(
          color: Color(0xFF2A2A2A),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(
                  onPressed: () => Get.back(),
                  child:
                      const Text('取消', style: TextStyle(color: Colors.white)),
                ),
                TextButton(
                  onPressed: () {
                    weight.value = selectedWeight;
                    Get.back();
                    _updateUserInfo();
                  },
                  child: const Text('确定',
                      style: TextStyle(color: Color(0xFF007AFF))),
                ),
              ],
            ),
            Expanded(
              child: ListWheelScrollView.useDelegate(
                itemExtent: 50,
                diameterRatio: 1.5,
                physics: const FixedExtentScrollPhysics(),
                onSelectedItemChanged: (index) {
                  selectedWeight = 30 + index;
                },
                childDelegate: ListWheelChildBuilderDelegate(
                  builder: (context, index) {
                    return Center(
                      child: Text(
                        '${30 + index} kg',
                        style:
                            const TextStyle(color: Colors.white, fontSize: 20),
                      ),
                    );
                  },
                  childCount: 171, // 30-200kg
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
